<?php

namespace ApiBundle\Controller;

use AdminBundle\Entity\LogApi;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

abstract class BaseController extends Controller
{
    protected $ip;
    protected $uri;
    protected $username;
    protected $startTime = 0;

    /**
     * API 返回格式
     * @param int $code
     * @param string $message
     * @param array $data
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function apiJson($code = 0, $message = '', $data = [])
    {
        $duration = (microtime(true) - $this->startTime) * 1000;

        $result = ['code' => $code, 'duration' => $duration, 'message' => $message, 'data' => $data];
        $jsonRespon = $this->json($result);
        $this->apiLog($jsonRespon->getContent(), 'response');
        return $jsonRespon;
    }

    /**
     * 接收终端数据,并且用各接口数据模版初始化,以免节点不存在
     * @param Request $request
     * @param array $data_template
     * @return mixed
     */
    protected function apiRequest(Request $request, array &$data_template)
    {
        $this->startTime = microtime(true);

        $this->ip = $request->getClientIp();
        $this->uri = $request->getRequestUri();
        $this->username = $this->getUser() ? $this->getUser()->getUsername() : '';

        $json = $request->getContent();

        $this->apiLog($json);

        $data = array_replace_recursive($data_template, json_decode($json, true) ?: []);

        return $data;
    }

    /**
     * HTTP 请求,响应日志
     * @param $content
     * @param string $action
     * @param string $name
     * @return int
     */
    protected function apiLog($content, $action = 'request', $name = '')
    {
        $logApi = new LogApi();
        $logApi->setCtime(new \DateTime())
            ->setIp($this->ip)
            ->setCreator($this->username)
            ->setAction($action)
            ->setContent($content)
            ->setUri($this->uri)
            ->setName($name);

        $em = $this->getDoctrine()->getManager();
        $em->persist($logApi);
        $em->flush();
        return $logApi->getId();
    }
}
